<template>
  <el-form ref="configForm" :show-message="false" :model="config" :size="size" :rules="rules" label-width="150px">
    <el-collapse v-model="activeName" accordion>
      <el-collapse-item title="生成参数配置" name="params">
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="tableName" label="表名称" prop="tableName">
              <el-input v-model="config.tableName" disabled placeholder="请输入表名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <el-input v-model="config.author" placeholder="请输入作者" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="包名" prop="packageName">
              <el-input v-model="config.packageName" placeholder="请输入包名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请求路径前缀" prop="requestMappingPrefix">
              <el-input v-model="config.requestMappingPrefix" placeholder="请输入请求路径前缀" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="tableName" label="后端模块名称" prop="moduleName">
              <el-input v-model="config.moduleName" placeholder="请输入后端模块名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="前端模块名称" prop="uiModuleName">
              <el-input v-model="config.uiModuleName" placeholder="请输入前端模块名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="占用栅格列数" prop="colSpan">
              <el-input-number v-model="config.colSpan" :min="1" :max="24" placeholder="请输入占用栅格列数" />
              <el-tooltip effect="dark" content="form表单中每一项占用栅格布局的列数，栅格总列数为24" placement="top">
                <i class="el-icon-info" style="width: 10px;height: 10px; margin-left: 10px;" />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="tableName" label="描述" prop="tableRemarks">
              <el-input v-model="config.tableRemarks" placeholder="请输入描述" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="过滤实体类属性" prop="excludeField">
              <el-select
                v-model="config.excludeField"
                style="width: 100%;"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请输入实体类属性"
              >
                <el-option
                  v-for="(item, index) in options.excludeFieldOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="!tableName" label="过滤表前缀" prop="excludeTablePrefix">
              <el-select
                v-model="config.excludeTablePrefix"
                style="width: 100%;"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请输入表前缀"
              >
                <el-option
                  v-for="(item, index) in options.excludeTablePrefixOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="!tableName" label="过滤表后缀" prop="excludeTableSuffix">
              <el-select
                v-model="config.excludeTableSuffix"
                style="width: 100%;"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请输入表后缀"
              >
                <el-option
                  v-for="(item, index) in options.excludeTableSuffixOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="tableName" label="父级目录" prop="parentMenuId">
              <el-cascader
                v-model="config.parentMenuId"
                style="width: 100%;"
                placeholder="输入目录名称搜索"
                :options="menuTree"
                :props="treeProps"
                :show-all-levels="false"
                filterable
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item>
              <el-checkbox v-if="config.parentMenuId" v-model="config.enableCache" :true-label="0" :false-label="1" :size="size">开启菜单缓存</el-checkbox>
              <el-checkbox v-model="config.enableImport" :true-label="0" :false-label="1" :size="size">生成导入</el-checkbox>
              <el-checkbox v-model="config.enableExport" :true-label="0" :false-label="1" :size="size">生成导出</el-checkbox>
              <el-checkbox v-model="config.enableLog" :true-label="0" :false-label="1" :size="size">生成Log注解</el-checkbox>
              <el-checkbox v-model="config.enableBuilder" :true-label="0" :false-label="1" :size="size">开启Builder模式</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="config.remark" type="textarea" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-collapse-item>
      <el-collapse-item title="生成模板配置" name="template">
        <div
          v-for="(item, index) in config.templateList"
          :key="index"
        >
          <span style="display: inline-block;width: 150px;">{{ item.key }}</span>
          <span style="display: inline-block;width: 150px;"><el-checkbox v-model="item.enable">生成</el-checkbox></span>
          <span v-if="'execute' in item" style="display: inline-block;width: 150px;">
            <el-checkbox v-model="item.execute">立即执行</el-checkbox>
            <el-popover trigger="hover" placement="top">
              <el-alert
                :closable="false"
                title="注意！！！多次生成将重复执行"
                description="勾选后，将在生成代码时立即执行生成的SQL"
                type="error"
              />
              <i slot="reference" class="el-icon-info" />
            </el-popover>
          </span>
          <span v-if="'enableExtendsCreateDTO' in item" style="display: inline-block;width: 150px;">
            <el-checkbox v-model="item.enableExtendsCreateDTO">继承createDTO</el-checkbox>
            <el-popover trigger="hover" placement="top">
              <el-alert
                :closable="false"
                title="注意事项"
                description="勾选后，在生成代码时将继承createDTO，实体类仅保留id属性"
                type="error"
              />
              <i slot="reference" class="el-icon-info" />
            </el-popover>
          </span>
        </div>
      </el-collapse-item>
    </el-collapse>
    <div style="display: flex;align-items: center;justify-content: center;margin-top: 15px;">
      <el-button :size="size" type="primary" @click="submit">提交</el-button>
      <el-button :size="size" type="info" @click="reset">重置</el-button>
      <el-button v-if="tableName" :size="size" @click="close">返回</el-button>
    </div>
  </el-form>
</template>

<script>
import {
  tableConfig,
  updateTableConfig,
  resetTableConfig,
  globalConfig,
  resetGlobalConfig,
  updateGlobalConfig
} from '@/api/dev/gen-config'
import { tree } from '@/api/system/menu'
import { mixin } from '@/views/pages/mixin/save'
import { toLastView } from '@/utils'
export default {
  mixins: [mixin],
  data() {
    return {
      activeName: 'params', // params | template
      tableName: this.$route.params.tableName, // 表名
      config: { // 配置项
        excludeField: [],
        excludeTablePrefix: [],
        excludeTableSuffix: []
      },
      menuTree: [], // 菜单树
      treeProps: { // 菜单树配置
        emitPath: false,
        checkStrictly: true,
        value: 'id',
        label: 'label'
      },
      options: { // 页面选择项
        excludeFieldOptions: [],
        excludeTablePrefixOptions: [],
        excludeTableSuffixOptions: []
      },
      rules: {
        tableName: [
          { required: true, message: '请输入表名称', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入作者', trigger: 'blur' }
        ],
        packageName: [
          { required: true, message: '请输入包名', trigger: 'blur' }
        ],
        requestMappingPrefix: [
          { required: true, message: '请输入请求路径前缀', trigger: 'blur' }
        ],
        moduleName: [
          { required: true, message: '请输入后端模块名称', trigger: 'blur' }
        ],
        uiModuleName: [
          { required: true, message: '请输入前端模块名称', trigger: 'blur' }
        ],
        tableRemarks: [
          { required: true, message: '请输入描述', trigger: 'blur' }
        ]

      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      if (this.tableName) {
        // 获取表配置
        this.getTableConfig()
        // 获取菜单树
        this.getMenuTree()
      } else {
        this.getGlobalConfig()
      }
    },
    // 获取全局配置
    getGlobalConfig() {
      globalConfig().then(res => {
        this.config = res.data
        this.handleConfig()
      })
    },
    // 获取表配置
    getTableConfig() {
      // 获取表配置信息
      const params = { tableName: this.tableName }
      tableConfig(params).then(res => {
        this.config = res.data
        this.handleConfig()
      })
    },
    // 获取菜单树
    getMenuTree() {
      tree({ parentId: 0 }).then(res => {
        this.menuTree = this.eachItem(res.data)
      })
    },
    // 处理配置
    handleConfig() {
      this.options.excludeFieldOptions = this.config.excludeField
      this.options.excludeTablePrefixOptions = this.config.excludeTablePrefix
      this.options.excludeTableSuffixOptions = this.config.excludeTableSuffix
    },
    // 递归处理子节点
    eachItem(tree) {
      tree = tree.filter(item => item.type === 1)
      tree.forEach(item => {
        item.children = this.eachItem(item.children)
        if (item.children.length === 0) {
          delete item.children
        }
      })
      return tree
    },
    // 保存
    submit() {
      this.$refs['configForm'].validate((valid, obj) => {
        if (valid) {
          const templateJson = {}
          this.config.templateList.forEach(item => {
            templateJson[item.key] = item
          })
          this.config.templateJson = templateJson
          if (this.tableName) {
            updateTableConfig(this.config).then(res => {
              this.$message.success('保存成功')
              this.close()
            })
          } else {
            updateGlobalConfig(this.config).then(res => {
              this.$message.success('保存成功')
              this.$emit('submit')
            })
          }
        } else {
          const field = []
          for (const key in obj) {
            field.push(obj[key][0].message)
          }
          this.$message.error(field[0])
          return false
        }
      })
    },
    // 重置
    reset() {
      this.$confirm('此操作将重置当前配置, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.tableName) {
          resetTableConfig(this.config.tableName).then(res => {
            this.init()
            this.$message.success('重置成功')
          })
        } else {
          resetGlobalConfig().then(res => {
            this.init()
            this.$message.success('重置成功')
          })
        }
      }).catch(() => {})
    },
    // 关闭页面
    close() {
      this.$store.dispatch('tagsView/delView', this.$route).then(({ visitedViews }) => {
        toLastView(visitedViews, this.$route)
        this.$emit('close')
      })
    }
  }
}
</script>
